package com.tegtech.starter.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.tegtech.starter.validator.annotation.ValueLength;

/**
 * 自定义参数长度校验，若参数有值则进行长度校验，否则不校验
 * @Author Jun
 * @date 2020年7月30日 下午5:39:23
 */
public class ValueLengthValidator implements ConstraintValidator<ValueLength, String> {

	private int min = 0;
	
	private int max = Integer.MAX_VALUE;
	
	@Override
    public void initialize(ValueLength constraintAnnotation) {
		min = constraintAnnotation.min();
		max = constraintAnnotation.max();
    }
	
	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		int length = 0;
		if(value == null || (length = value.trim().length()) == 0) {
			return true;
		}
		return length >= min && length <= max;
	}

}
